<?php
namespace Model;

require_once("Model/quizModel.php");

class quizDAL{
	private static $mainTable = "quiz";
	private static $questionTable = "questions";
	private $mysqli;
	
	public function __construct($mysqli){
		$this->mysqli = $mysqli;
	}
	
	/**
	 * @throws Exception if the table cannot be created
	 */
	public function createTable(){
		$sql = "CREATE TABLE IF NOT EXISTS `" . self::$mainTable . "` 
		(
		    `pk` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
		    `quizname` VARCHAR(255)
		)
		ENGINE = MyISAM;";
		   
		if ($this->mysqli->query($sql) === false){
			throw new \Exception("Skapandet av MySQL table misslyckades. Meddelande: " . $this->mysqli->error);
		}
		
		$this->createQuestionTable();
	}
	
	/**
	 * @throws Exception if the table cannot be created
	 */
	private function createQuestionTable(){
		$sql = "CREATE TABLE IF NOT EXISTS `" . self::$questionTable . "` 
		    (
		        `pk` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
		        `fk` INT FOREIGN KEY REFERENCES " . self::$mainTable . "(pk),
		        `question` VARCHAR(255),
		        `a1` VARCHAR(255),
		        `a2` VARCHAR(255),
		        `a3` VARCHAR(255),
		        `corranswer` VARCHAR(255)
		    )
		    ENGINE = MyISAM;";
		   
		if ($this->mysqli->query($sql) === false){
	      throw new \Exception("Skapandet av MySQL table misslyckades. Meddelande: " . $this->mysqli->error);
		}
	}
	
	/**
     * @param $quiz (The quiz to be inserted)
	 * 
     * @throws \Exception (If there is any problem with inserting)
    */
    public function insertQuiz(\Model\quizModel $quiz){
	    $sql = "INSERT INTO " . self::$mainTable . " 
	        (
	            quizname
	        ) 
	        VALUES(?)";
	    $statement = $this->mysqli->prepare($sql);
	    if ($statement === false) {
	        throw new \Exception("Prepare av MySQL misslyckades. Meddelande: " . $this->mysqli->error);
	    }
	
	    if ($statement->bind_param("s", $quiz->quizName) === false) {
	        throw new \Exception("Knytning av parametrar till databas misslyckades. Meddelande: " . $statement->error);
	    }
	
	    if ($statement->execute() === false) {
	        throw new \Exception("Utförandet av SQL misslyckades. Meddelande: " . $statement->error);
	    }
		
		$this->insertQuestions($quiz);
    }
	
	/**
	 * @param $quiz (The quiz to be inserted)
	 */
	public function insertQuestions(\Model\quizModel $quiz){
		$i = 0;
		$answerOptions = array_chunk($quiz->answerOptions, 3);
		
		foreach($answerOptions as $answerOption){
			$sql = "INSERT INTO " . self::$questionTable . " 
		        (
		        	fk,
		            question,
		            a1,
		            a2,
		            a3,
		            corranswer
		        ) 
		        VALUES(LAST_INSERT_ID(), ?, ?, ?, ?, ?)";
		    $statement = $this->mysqli->prepare($sql);
		    if ($statement === false) {
		        throw new \Exception("Prepare av MySQL misslyckades. Meddelande: " . $this->mysqli->error);
		    }
		
		    if ($statement->bind_param("sssss", $quiz->questions[$i],
		    								    $answerOption[0],
											    $answerOption[1],
											    $answerOption[2],
											    $quiz->answers[$i]) === false) {
		        throw new \Exception("Knytning av parametrar till databas misslyckades. Meddelande: " . $statement->error);
		    }
		
		    if ($statement->execute() === false) {
		        throw new \Exception("Utförandet av SQL misslyckades. Meddelande: " . $statement->error);
		    }		
			$i++;
		}	
	}
	
	//TODO: Implement this for quiz
	/**
	 * @return array (containing all quizes, if any)
	 */
	public function getAllQuizzes(){
        $sql = "SELECT `quizname` FROM " . self::$mainTable . " WHERE 1
        	    SELECT `question`, `a1`, `a2`, `a3`, `corranswer` FROM " . self::$questionTable . " 
        	    WHERE " . self::$questionTable . "`fk` = ." . self::$mainTable . "`pk`;";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {
            throw new \Exception("Prepare av MySQL misslyckades. Meddelande: " . $this->mysqli->error);
        }

        if ($statement->execute() === false) {
            throw new \Exception("Hämtningen av quiz misslyckades. Meddelande: " . $statement->error);
        }
 
        $result = $statement->get_result();

		$qs = array();
		$aoptions = array();
		$corranswer = array();
		
        while ($object = $result->fetch_array(MYSQLI_ASSOC))
        {
        	foreach($object["question"] as $question){
            	$qs[] = $question;
				$aoptions[] = $object["a1"];
				$aoptions[] = $object["a2"];
				$aoptions[] = $object["a3"];
				$corranswers[] = $object["corranswer"];
			}
			$ret[] = new quizModel($object["quizname"], $qs, $corranswer, $aoptions);
        }
 
        return $ret;
	}
}
